package com.tanqin.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tanqin.constant.RedisConstant;
import com.tanqin.dao.SetmealDao;
import com.tanqin.entity.PageResult;
import com.tanqin.entity.QueryPageBean;
import com.tanqin.pojo.Setmeal;
import com.tanqin.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        // 添加体检套餐
        setmealDao.add(setmeal);

        // 设置体检套餐和检查组多对多关系
        Integer setmealId = setmeal.getId();
        this.setSetmealAndCheckGroup(setmealId, checkgroupIds);
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());


        // 新增套餐后，生成静态页面
        generateMobileStaticHtml();
    }

    /**
     * 生成静态页面
     */
    public void generateMobileStaticHtml() {
        List<Setmeal> list = setmealDao.findAll();
        // 生成套餐列表页静态页面
        generateMobileSetmealListHtml(list);
        // 生成套餐详情页静态页面
        generateMobileSetmealDetailHtml(list);
    }

    // 生成套餐列表页静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        map.put("setmealList", list);
        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    // 生成套餐详情页静态页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        Map map = null;
        for (Setmeal setmeal : list) {
            map = new HashMap<String, Object>();
            map.put("setmeal", setmealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    /**
     * 生成静态页面 - 通用方法
     *
     * @param templateName 模板文件名称
     * @param htmlPageName 生成 html 页面名称
     * @param dataMap      替换的数据
     */
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        // 获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 获取模板对象
            Template template = configuration.getTemplate(templateName);
            // 创建输出流对象
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            // 输出文件
            template.process(dataMap, out);
            // 关闭输出流
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        // 条件查询
        Page<Setmeal> page = setmealDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    public void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        Map<String, Integer> map = null;
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {

        return setmealDao.findSetmealCount();
    }
}
